<?php
	define('FORGOT_PWD_SERVICE',true);
	require_once './ForgotPwdService.class.php';
		
	require_once '../Classes/User.class.php';
	require_once '../Tool/Common/PasswordHash.php';
	require_once '../Tool/Common/PrepareInput.php';
	
	//Generate random string with 10 length
	function generateRandomString($length = 10) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}
	
	//Create a ForgotPwdService class
	$forgotPwdService = new ForgotPwdService();
	
	if(!empty($_POST['hashValue'])){
		$hashValue=$_POST['hashValue'];
	}
	//Reset Pwd by username
	if(empty($_POST['tokenKey'])){
		header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=1');
		exit();	
	}else{
		//retrieve token key
		$tokenKey=prepareInput($_POST['tokenKey']);
		if (!preg_match("/^[0-9A-Za-z]*$/",$tokenKey)){
			header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=2');
			exit();
		}
		//retrieve token key
		$res=$forgotPwdService->retrieveTokenKeyInfo($tokenKey,$hashValue);

		if(empty($res)){
			header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=3');
			exit();
		}else{
			$expireTime=$res['ExpireTime'];
			$expired=$res["Expired"];

			//Check token key expired or not 
			if($expireTime<date('Y-m-d H:i:s',time())||$expired=="1"){
				header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=4');
				exit();
			}else{
				//Retrieve user email address
				session_start();
				$userEmailAddress=$_SESSION[$hashValue];
			
				//Generate random password
				$randomPassword=generateRandomString();
				
				//Hash random password
				$newPassword=create_hash($randomPassword);

				//Send email
				$emailRes=$forgotPwdService->sendNewPwd($userEmailAddress,$randomPassword);

				//Determine send email result
				if($emailRes){
					//Success	
					//Update password into database
					$res=$forgotPwdService->updatePwdByEmailAddress($userEmailAddress,$newPassword);

					//update token
					$res2=$forgotPwdService->updateTokenByTokenKey($tokenKey);	

					if($res === true && $res2===true){
						header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=5');
						exit();
					}else{
						header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=7');
						exit();
					}

				}else{
					header('Location: ../Token.php?hashValue='.$hashValue.'&&msgno=6');
					exit();	
				}
			}
		}
	}		
?>